package com.bt.lms.ui.action.school_education.stu_basic.familyMember;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bt.lms.constants.BOConstant;
import com.bt.lms.constants.StuStatusBizTypeConstant;
import com.bt.lms.entity.FamilyMemberInfo;
import com.bt.lms.network.msg.RespMsg;
import com.bt.lms.ui.page.sys.style.BtnStyle;
import com.bt.lms.ui.vo.school_education.family_member.AddFamilyMemberVo;
import com.bt.lms.network.msg.ReqMsg;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import org.apache.commons.beanutils.BeanUtils;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
 * 家庭成员里添加功能的验证事件
 */
public class AddVerifyAction implements EventHandler {

    private VBox vBox;

    private HBox familyHBox;

    private List list;

    public AddVerifyAction(VBox vBox, HBox familyHBox, List list) {
        this.vBox = vBox;
        this.familyHBox = familyHBox;
        this.list = list;

    }

    @Override
    public void handle(Event event) {
        //1.获取用户输入
        AddFamilyMemberVo addFamilyMemberVo = getInput();
        //2.验证用户输入是否合法
        String verifyMsg = getVerifyInput(addFamilyMemberVo);
        //3.组包 组成消息
        byte[] bytes = null;
        if (null == verifyMsg) {
            bytes = handleReqMsg(addFamilyMemberVo);
        } else {
            return;
        }
        //4.组网
        Socket socket = getNet();
        //5.发送消息对象
        boolean flag = sendReqMsg(socket, bytes,addFamilyMemberVo);


    }


    /**
     * 发送消息对象
     *
     * @param socket 网
     * @param bytes  消息
     * @return 布尔值
     */
    private boolean sendReqMsg(Socket socket, byte[] bytes,AddFamilyMemberVo addFamilyMemberVo) {
        try {
            //获取流，写过去
            OutputStream out = socket.getOutputStream();
            out.write(bytes);
            out.flush();


            //响应
            InputStream in = socket.getInputStream();
            byte[] buf = new byte[1024];
            in.read(buf);
            //调用方法将字节流转为响应消息对象
            RespMsg respMsg = RespMsg.toRespMsg(buf);
            //获取消息内容
            String data = respMsg.getData();
            //如果消息内容不为空，则成功
            if (data != null){
                Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                alert.setContentText("添加成功");
                alert.showAndWait();
            }

            //界面回显
            VBox pageBox = echoPage(addFamilyMemberVo);
            ObservableList<Node> children = this.vBox.getChildren();
            int size = children.size();
            this.vBox.getChildren().set(size-1,pageBox);


            //关闭资源
            out.close();
            socket.close();


        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        return true;
    }

    /**
     * 界面回显
     * @param addFamilyMemberVo vo对象、
     * @return 盒子
     */
    private VBox echoPage(AddFamilyMemberVo addFamilyMemberVo) {
        double baseWidth = 1230;
        VBox familyVBox = new VBox();
        ObservableList<Node> children = familyVBox.getChildren();
        HBox hBox = new HBox();
        hBox.setPrefWidth(baseWidth);
        hBox.setAlignment(Pos.CENTER_RIGHT);
        hBox.setSpacing(10);
        Insets insets1 = new Insets(10, 30, 10, 10);
        hBox.setPadding(insets1);
        Button editBtn = new Button("💻编辑");
        Button deleteBtn = new Button("❌删除");
        hBox.getChildren().add(editBtn);
        hBox.getChildren().add(deleteBtn);
        //按钮样式
        BtnStyle.saveBtn(editBtn);
        BtnStyle.cancelBtn(deleteBtn);
        editBtn.setCursor(Cursor.HAND);
        deleteBtn.setCursor(Cursor.HAND);
        children.add(hBox);
        //事件
        FamilyMemberEditAction familyMemberEditAction = new FamilyMemberEditAction(vBox,list,familyHBox);
        editBtn.setOnAction(familyMemberEditAction);
        //删除按钮
        deleteBtn.setOnAction(event -> {
            Alert alert = new Alert(Alert.AlertType.NONE);
            alert.setHeaderText(null);
            alert.setTitle("删除");
            DeleteVerifyAction deleteVerifyAction = new DeleteVerifyAction(alert,vBox,list);
            deleteVerifyAction.handle();
            alert.getDialogPane().setPrefWidth(500);
            alert.getDialogPane().setPrefHeight(300);
            alert.setGraphic(deleteVerifyAction);
            alert.showAndWait();
        });

        //家庭成员信息的主盒子
        HBox totalHBox = new HBox();
        totalHBox.setPrefWidth(baseWidth);
        totalHBox.setSpacing(10);

        VBox one1 = new VBox();
        one1.setPrefWidth(baseWidth / 8);
        one1.setSpacing(10);
        Label relationLab = new Label("关系");
        Label jobUnitLab = new Label("成员工作单位");
        Label nationLab = new Label("民族");
        Label professionalSkillLab = new Label("专业技术职务");
        Label isEmergencyContact = new Label("是否紧急联系人");
        one1.getChildren().addAll(relationLab, jobUnitLab, nationLab, professionalSkillLab,isEmergencyContact);
        totalHBox.getChildren().add(one1);

        VBox one2 = new VBox();
        one2.setPrefWidth(baseWidth / 6);
        one2.setSpacing(10);
        Label relationMes = new Label(addFamilyMemberVo.getRelation());
        Label jobUnitLabMes = new Label(addFamilyMemberVo.getWorkUnit());
        Label nationMes = new Label(addFamilyMemberVo.getNation());
        Label professionalSkillLabMes = new Label(addFamilyMemberVo.getDuty());
        String leave = null;
        if (addFamilyMemberVo.getIsEmergencyContact() == BOConstant.FAMILY_MEMBER_IS_EMERGENCY_CONTACT_YES){
            leave = "是";
        }
        if (addFamilyMemberVo.getIsEmergencyContact() == BOConstant.FAMILY_MEMBER_IS_EMERGENCY_CONTACT_NO){
            leave = "否";
        }
        Label isLab = new Label(leave);
        one2.getChildren().addAll(relationMes, jobUnitLabMes, nationMes, professionalSkillLabMes,isLab);
        totalHBox.getChildren().add(one2);


        VBox one3 = new VBox();
        one3.setPrefWidth(baseWidth / 8);
        one3.setSpacing(10);
        Label memberNameLab = new Label("成员姓名");
        Label practitionersLab = new Label("从业");
        Label nationalityLab = new Label("国籍/地区");
        Label jobRankLab = new Label("职务级别");
        one3.getChildren().addAll(memberNameLab, practitionersLab, nationalityLab, jobRankLab);
        totalHBox.getChildren().add(one3);

        VBox one4 = new VBox();
        one4.setPrefWidth(baseWidth / 6);
        one4.setSpacing(10);
        Label memberNameLabMes = new Label(addFamilyMemberVo.getName());
        Label practitionersLabMes = new Label(addFamilyMemberVo.getJob());
        String nationality = null;
        switch (addFamilyMemberVo.getNationality()){
            case 1://BOConstant.FAMILY_MEMBER_NATIONALITY_MAINLAND
                nationality = "中国大陆";
                break;
            case 2://BOConstant.FAMILY_MEMBER_NATIONALITY_HK
                nationality = "中国香港";
                break;
            case 3://BOConstant.FAMILY_MEMBER_NATIONALITY_FORMOSA
                nationality = "中国台湾";
                break;
            case 4://BOConstant.FAMILY_MEMBER_NATIONALITY_MACAO
                nationality = "中国澳门";
                break;
        }
        Label nationalityMes = new Label(nationality);
        Label jobRankLabMes = new Label(addFamilyMemberVo.getDutyRank());
        one4.getChildren().addAll(memberNameLabMes, practitionersLabMes, nationalityMes, jobRankLabMes);
        totalHBox.getChildren().add(one4);


        VBox one5 = new VBox();
        one5.setPrefWidth(baseWidth / 8);
        one5.setSpacing(10);
        Label birthDataLab = new Label("出生年月");
        Label phoneLab = new Label("电话");
        Label healthConditionLab = new Label("健康状况");
        Label emileLab = new Label("电子邮箱");
        one5.getChildren().addAll(birthDataLab, phoneLab, healthConditionLab, emileLab);
        totalHBox.getChildren().add(one5);

        VBox one6 = new VBox();
        one6.setPrefWidth(baseWidth / 6);
        one6.setSpacing(10);
        Label birthDataLabMes = new Label(addFamilyMemberVo.getBirthday().toString());
        Label phoneLabMes = new Label(addFamilyMemberVo.getPhone());
        Label healthConditionLabMes = new Label(addFamilyMemberVo.getHealthCondition());
        Label emileLabMes = new Label(addFamilyMemberVo.getEmail());
        one6.getChildren().addAll(birthDataLabMes, phoneLabMes, healthConditionLabMes, emileLabMes);
        totalHBox.getChildren().add(one6);
        children.add(totalHBox);

        return familyVBox;
    }

    /**
     * 读取响应包
     *
     * @param in 读流
     * @return 体内容
     */
    private String readBytes(InputStream in) {
        byte[] bytes = null;
        try {
            bytes = new byte[1024];
            in.read(bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        RespMsg respMsg = RespMsg.toRespMsg(bytes);


        return respMsg.getData();
    }

    /**
     * 组网
     *
     * @return 网
     */
    private Socket getNet() {
        String ip = "127.0.0.1";
        int port = 8888;
        Socket socket = null;
        try {
            socket = new Socket(ip, port);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return socket;
    }


    /**
     * 组包
     *
     * @param addFamilyMemberVo vo对象
     * @return 消息
     */
    private byte[] handleReqMsg(AddFamilyMemberVo addFamilyMemberVo) {
        //消息
        ReqMsg reqMsg = new ReqMsg();
        //业务类型
        reqMsg.setBizType(StuStatusBizTypeConstant.FAMILY_MEMBER_BIZ_TYPE_ADD);
        //请求id
        reqMsg.setReqId(new Date().getTime());
        //entity对象
        FamilyMemberInfo familyMemberInfo = new FamilyMemberInfo();
        try {
            //将bo复制到entity里
            BeanUtils.copyProperties(familyMemberInfo,addFamilyMemberVo);
            familyMemberInfo.setId(1L);
            familyMemberInfo.setStuBasicInfoID(1L);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        //将对象转为json
        String familyStr = JSON.toJSONString(familyMemberInfo);
        reqMsg.setData(familyStr);


        return  reqMsg.toBytes();
    }


    /**
     * 验证用户输入是否合法
     *
     * @param addFamilyMemberVo vo对象
     * @return msg 消息
     */
    private String getVerifyInput(AddFamilyMemberVo addFamilyMemberVo) {
        String msg = "";

        //关系
        if (addFamilyMemberVo.getRelation().equals("")) {
            msg += "关系为必填，请输入\r\n";
        } else {
            if (addFamilyMemberVo.getRelation().length() > 24) {
                msg += "关系在1-24位之间\r\n";
            }
        }


        //成员姓名
        if (addFamilyMemberVo.getName().equals("")) {
            msg += "成员姓名为必填，强输入\r\n";
        } else {
            if (addFamilyMemberVo.getName().length() > 24) {
                msg += "成员姓名在1-24位之间\r\n";
            }
        }

        //出生年月
        if (addFamilyMemberVo.getBirthday() == null) {
            msg += "出生年月为必填，请输入\r\n";
        } else {
            LocalDate birthday = addFamilyMemberVo.getBirthday();
            int year = birthday.getYear();
            int year1 = LocalDate.now().getYear();
            if (year > year1 || year1 - year > 150) {
                msg += "出生年月在当前时间之前，在150年内\r\n";
            }
        }

        //成员工作单位
        if (addFamilyMemberVo.getWorkUnit().equals("")) {
            msg += "成员工作单位为必填，请输入\r\n";
        } else {
            if (addFamilyMemberVo.getWorkUnit().length() > 24) {
                msg += "成员工作单位在1-24位之间\r\n";
            }
        }

        //从业
        if (!addFamilyMemberVo.getJob().equals("")) {
            if (addFamilyMemberVo.getJob().length() > 24) {
                msg += "从业在1-24位之间\r\n";
            }
        }

        //电话
        if (addFamilyMemberVo.getPhone().equals("")) {
            msg += "电话为必填，请输入\r\n";
        } else {
            if (addFamilyMemberVo.getPhone().length() > 24) {
                msg += "电话在1-24位之间\r\n";
            }
        }

        //民族
        if (addFamilyMemberVo.getNation() == null) {
            msg += "民族为必填，请输入\r\n";
        } else {

        }

//        //国籍/地区
        if (addFamilyMemberVo.getNationality() == null) {
            msg += "国籍/地区为必填，请输入\r\n";
        } else {

        }

        //健康状况
        if (addFamilyMemberVo.getHealthCondition().equals("")) {
            msg += "健康状况为必填，请输入\r\n";
        } else {
            if (addFamilyMemberVo.getHealthCondition().length() > 24) {
                msg += "健康状况在1-24位之间\r\n";
            }
        }

        //专业技术职务
        if (!addFamilyMemberVo.getDuty().equals("")) {
            if (addFamilyMemberVo.getDuty().length() > 24) {
                msg += "专业技术职务在1-24位之间\r\n";
            }
        }

        //职务级别
        if (!addFamilyMemberVo.getDutyRank().equals("")) {
            if (addFamilyMemberVo.getDutyRank().length() > 24) {
                msg += "职务级别在1-24位之间\r\n";
            }
        }


        //电子邮箱
        if (!addFamilyMemberVo.getEmail().equals("")) {
            if (addFamilyMemberVo.getEmail().length() > 24) {
                msg += "电子邮箱在1-24位之间\r\n";
            }
        }

        //是否紧急联系人
        if (addFamilyMemberVo.getIsEmergencyContact() == null) {
            msg += "紧急联系人必填\r\n";
        }

        if (!msg.equals("")) {
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText(msg);
            alert.show();
        }

        if (msg.equals("")) {
            msg = null;
        }


        return msg;
    }

    /**
     * 获取用户输入
     *
     * @return vo对象
     */
    private AddFamilyMemberVo getInput() {
        AddFamilyMemberVo addFamilyMemberVo = new AddFamilyMemberVo();
        //关系
        TextField relationTF = (TextField) this.vBox.lookup("#relation");
        String relationStr = relationTF.getText().trim();
        addFamilyMemberVo.setRelation(relationStr);
        //成员姓名
        TextField nameTF = (TextField) this.vBox.lookup("#name");
        String nameStr = nameTF.getText().trim();
        addFamilyMemberVo.setName(nameStr);
        //出生年月
        DatePicker birthdayDP = (DatePicker) this.vBox.lookup("#birthday");
        if (!(birthdayDP.getValue() == null)) {
            LocalDate value = birthdayDP.getValue();
            addFamilyMemberVo.setBirthday(value);
        }
        //成员工作单位
        TextField workUnitTF = (TextField) this.vBox.lookup("#workUnit");
        String unitStr = workUnitTF.getText().trim();
        addFamilyMemberVo.setWorkUnit(unitStr);
        //从业
        TextField jobTF = (TextField) this.vBox.lookup("#job");
        String jobStr = jobTF.getText().trim();
        addFamilyMemberVo.setJob(jobStr);
        //电话
        TextField phoneTF = (TextField) this.vBox.lookup("#phone");
        String phoneStr = phoneTF.getText().trim();
        addFamilyMemberVo.setPhone(phoneStr);
        //民族
        ComboBox nationTF = (ComboBox) this.vBox.lookup("#nation");
        String nationStr = (String) nationTF.getValue();
        addFamilyMemberVo.setNation(nationStr);
        //国籍/地区
        ComboBox nationalityTF = (ComboBox) this.vBox.lookup("#nationality");
        String value = (String) nationalityTF.getValue();
        int rs = -1;
        switch (value) {
            case "中国大陆":
                rs = BOConstant.FAMILY_MEMBER_NATIONALITY_MAINLAND;
                break;
            case "中国香港":
                rs = BOConstant.FAMILY_MEMBER_NATIONALITY_HK;
                break;
            case "中国台湾":
                rs = BOConstant.FAMILY_MEMBER_NATIONALITY_FORMOSA;
                break;
            case "中国澳门":
                rs = BOConstant.FAMILY_MEMBER_NATIONALITY_MACAO;
                break;

        }
        addFamilyMemberVo.setNationality(rs);

        //健康状况
        TextField healthConditionTF = (TextField) this.vBox.lookup("#healthCondition");
        String healthStr = healthConditionTF.getText().trim();
        addFamilyMemberVo.setHealthCondition(healthStr);
        //专业技术职务
        TextField dutyTF = (TextField) this.vBox.lookup("#duty");
        String dutyStr = dutyTF.getText().trim();
        addFamilyMemberVo.setDuty(dutyStr);
        //职务级别
        TextField dutyRankTF = (TextField) this.vBox.lookup("#dutyRank");
        String dutyRankStr = dutyRankTF.getText().trim();
        addFamilyMemberVo.setDutyRank(dutyRankStr);
        //电子邮箱
        TextField emailTF = (TextField) this.vBox.lookup("#email");
        String emailStr = emailTF.getText().trim();
        addFamilyMemberVo.setEmail(emailStr);
        //是否紧急联系人
        RadioButton yes = (RadioButton) this.vBox.lookup("#yesRDB");
        RadioButton no = (RadioButton) this.vBox.lookup("#noRDB");
        if (yes.isSelected()) {
            addFamilyMemberVo.setIsEmergencyContact(BOConstant.FAMILY_MEMBER_IS_EMERGENCY_CONTACT_YES);
        }
        if (no.isSelected()) {
            addFamilyMemberVo.setIsEmergencyContact(BOConstant.FAMILY_MEMBER_IS_EMERGENCY_CONTACT_NO);
        }


        return addFamilyMemberVo;
    }

}
